package com.ecplatform.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.ecplatform.common.utils.UserContext;
import com.ecplatform.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
@Slf4j
public class UserInfoInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    /**
     * 进入请求前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的用户信息
        String userInfo = request.getHeader("user-info");

        // 2.判断是否为空
        if (!StrUtil.isBlank(userInfo)) {
            // 不为空则保存到ThreadLocal中
            UserContext.setUserId(Long.valueOf(userInfo));
            log.info("设置上下文：{}", UserContext.getUserId());
        }

        // 3.放行
        return true;
    }

    /**
     * 请求处理之后拦截，用于清理上下文/释放资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除上下文
        UserContext.clear();
        log.info("上下文已清除：{}", UserContext.getUserId());
    }
}
